﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace CleanLite.Infrastructure.Authentication.Jwt
{
    public class JwtTokenGenerator(IOptions<JwtSettings> options) : IJwtTokenGenerator
    {
        private readonly JwtSettings options = options.Value;

        public string GenerateToken(TokenModel model)
        {
            var claims = new List<Claim>()
            {
                new(JwtRegisteredClaimNames.Jti, model.Id),
                new(JwtRegisteredClaimNames.Iss,options.Issuer),
                new(JwtRegisteredClaimNames.Aud,options.Audience),
                new(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(options.ExpiryMinutes)).ToUnixTimeSeconds()}"),
                new(JwtRegisteredClaimNames.Iat,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new(ClaimTypes.Name,model.Name)//姓名
            };
            claims.AddRange(model.Role.Split(',').Select(a => new Claim(ClaimTypes.Role, a)));

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.Secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddMinutes(options.ExpiryMinutes);

            var token = new JwtSecurityToken(
            issuer: options.Issuer,
            audience: options.Audience,
            claims: claims,
            expires: expires,
            signingCredentials: creds
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}